<template>
    <a-modal
        v-model:visible="showModal"
        :title="title"
        :width="420"
        :destroyOnClose="true"
        :maskClosable="false"
        :confirmLoading="loading"
        @ok="onSubmit"
        @cancel="handleCancle"
    >
        <a-form class="dept-model" layout="horizontal" :model="formState" :rules="rules" ref="formRef">
            <!-- 商户名称 -->
            <a-form-item class="full-width" :label="t('yl.parentAreaCodeLabel')" name="parentAreaCode">
                <a-tree-select
                    v-model:value="formState.parentAreaCode"
                    style="width: 100%"
                    :tree-data="treeData"
                    allow-clear
                    :show-checked-strategy="'SHOW_PARENT'"
                    :dropdownClassName="'yl-treeselect'"
                    :placeholder="t('yl.parentAreaCodeLabel')"
                    :load-data="onLoadData"
                />
            </a-form-item>
            <!-- 收银编号 -->
            <a-form-item class="full-width" :label="t('yl.areaNameForm')" name="areaName">
                <a-input v-model:value="formState.areaName" :placeholder="t('yl.areaNameForm')" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>
<script lang="ts">
import { computed, defineComponent, reactive, ref, watch, onMounted, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import _ from 'lodash';
import { Pagination, PaginationQuery } from '@/types/table';
import { getArea } from '@/api/merchant';
interface DeptState {
    parentAreaCode: string;
    areaName: string | number;
    id: string | number;
}

// 表单校验规则
const initRules = (t: fn) => {
    return {
        // parentAreaCode: [{ required: true, message: t('yl.parentAreaCodeLabel'), trigger: 'blur' }],
        areaName: [{ required: true, message: t('yl.areaNameLable'), trigger: 'blur' }],
    };
};

export default defineComponent({
    name: 'roleModel',
    components: {},
    props: {
        visible: {
            type: Boolean,
            default: () => false,
        },

        title: {
            type: String,
        },
        loading: {
            type: Boolean,
            default: () => false,
        },
        dept: {
            type: Object,
        },
        CountryData: {
            type: Object,
        },
    },
    emits: ['submit', 'cancle'],
    setup(props, { emit }) {
        const { t } = useI18n();
        const tableQuery: PaginationQuery = reactive({
            page: 0,
            size: 9,
            sort: 'id,desc',
            parentAreaCodeIsNull: true,
        });
        const state = reactive({
            treeData: [] as TreeDataItem[],
        });
        const showModal = computed(() => props.visible);
        // const country = computed(() => props.selectCountry as NormalObj[]);
        const industryList = ref<any>([]);
        const countryRegionList = ref<any>([]);

        const formState: DeptState = reactive({
            parentAreaCode: '', // 设备编号
            areaName: '',
            id: '',
        });
        // 编辑时赋值

        const {
            parentAreaCode, // 设备编号
            areaName,
            id,
        } = props.dept as NormalObj;
        formState.parentAreaCode = parentAreaCode;
        formState.areaName = areaName;
        formState.id = id;
        // watch(
        //     () => props.dept,
        //     (dept) => {
        //         // if (_.isEmpty(dept)) return;
        //         console.log(dept);
        //         const {
        //             parentAreaCode, // 设备编号
        //             areaName,
        //             id,
        //         } = dept as NormalObj;
        //         formState.parentAreaCode = parentAreaCode;
        //         formState.areaName = areaName;

        //         formState.id = areaName;
        //     }
        // );

        onMounted(() => {
            handleInitDepts();
        });
        // 表单校验
        const rules = initRules(t);
        const formRef = ref();
        // 提交
        const onSubmit = () => {
            formRef.value.validate().then(() => {
                console.log(formState);
                emit('submit', formState);
            });
        };

        // 取消
        const handleCancle = () => {
            return emit('cancle');
        };

        // 获取所有区域
        const handleInitDepts = async () => {
            const { content } = await getArea(tableQuery);
            console.log(content);
            if (content && !content.length) return;

            state.treeData = content.map((item: any) => {
                return {
                    title: item.areaName,
                    key: item.areaCode,
                    value: item.areaCode,
                    isLeaf: false,
                    children: [],
                };
            });
        };
        // 异步加载树节点
        const onLoadData = (treeNode: { [x: string]: any }) => {
            return new Promise(async (resolve: (value?: unknown) => void) => {
                const { key } = treeNode.dataRef;
                const params = {
                    parentAreaCode: key,
                };
                let { content } = await getArea(params);
                if (!content.length) {
                    return resolve();
                }
                content = content.map((item) => {
                    return {
                        title: item.areaName,
                        key: item.areaCode,
                        value: item.areaCode,
                        isLeaf: item.leaf,
                        pId: key,
                    };
                });
                treeNode.dataRef.children = content;
                resolve();
            });
        };
        return {
            industryList,
            formRef,
            showModal,
            formState,
            t,
            rules,
            onSubmit,
            handleCancle,
            countryRegionList,
            tableQuery,
            ...toRefs(state),
            onLoadData,
        };
    },
});
</script>
<style lang="scss" scoped>
.dept-model {
    @include flexWrap;
    width: 100%;
    .ant-form-item {
        @include flex;
        width: 50%;
        margin-right: 0;
        padding-right: $width10;
        margin-bottom: $width8;
        :deep .ant-form-item-label {
            flex-basis: $formLabel;
        }
        :deep .ant-form-item-control-wrapper {
            flex: 1;
        }
        :deep .ant-form-item-children,
        :deep .ant-input-number {
            width: 100%;
        }
        &.full-width {
            width: 100%;
        }
    }
}
</style>
